using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarlosAg.ExcelXmlWriter;
using Medianamik.Globalization;
using Medianamik.Globalization.Utilities;
using System.IO;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.ModalWindows
{
    public partial class ImportResourceWindow : BasePage
    {
        protected MedianamikResourceDataManager Manager = new MedianamikResourceDataManager();

        protected void Import(object sender, EventArgs e)
        {
            if (IsValid)
            {
                if (RadUpload1.UploadedFiles.Count > 0)
                {
                    var wb = new Workbook();
                    var manager = new MedianamikResourceDataManager();
                    
                    foreach (UploadedFile file in RadUpload1.UploadedFiles)
                    {
                        wb.Load(file.InputStream);
                        var resources = wb.ToResources();

                        foreach (var resource in resources)
                           manager.UpdateOrAdd(resource);
                    }
                }
                else
                {
                    DisplayMessage((string)GetGlobalResourceObject("Medianamik_ResourceManagement", "NoFileSelected"));
                }

                DeleteFiles();

                ScriptManager.RegisterStartupScript(this, typeof(DeleteResourceWindow),
                    "CloseWindow", "closeWindow('ReloadResourceSets');", true);
            }
        }

        protected void UploadServerValidate(object source, ServerValidateEventArgs e)
        {
            e.IsValid = (RadUpload1.InvalidFiles.Count == 0);
        } 

        void DisplayMessage(string message)
        {
            mesageLiteral.Visible = true;
            mesageLiteral.Text = message;
        }

        private void DeleteFiles()
        {
            var targetFolder = Server.MapPath(RadUpload1.TargetFolder);
            var targetDir = new DirectoryInfo(targetFolder);

            foreach (var file in targetDir.GetFiles())
            {
                if ((file.Attributes & FileAttributes.ReadOnly) == 0) file.Delete();
            }
        }
    }
}